package java_thinking.unit_21.Exercise.collection;

import java.util.concurrent.*;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2019/7/22 10:48
 */

public class ConcurrentLinkedQueueTest {
    private static ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
    /**
     * 线程个数
     */
    private static int count = 5;
    /**
     * 线程池
     */
    private static ExecutorService es = Executors.newFixedThreadPool(5);
    private static CyclicBarrier barrier = new CyclicBarrier(5, new Runnable() {
        @Override
        public void run() {
            System.out.println("shutdownNow");
            es.shutdown();
        }
    });


    public static void main(String[] args) {
        es.submit(new Add1());
        for (int i = 0; i < 5; i++) {
            es.submit(new Add());
        }
    }

    static class Add implements Runnable {

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " ready to add");
                barrier.await();
                queue.add(Thread.currentThread().getName());
                System.out.println(Thread.currentThread().getName() + " added");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
    static class Add1 implements Runnable {

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " ready to add-");
                barrier.await();
                queue.add(Thread.currentThread().getName());
                System.out.println(Thread.currentThread().getName() + " added-");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
